import { Request, Response } from 'express';
import authService from '@/service/authService';
import logger from '@/utils/logger';
import { ResponseUtil } from '@/utils/R';



class AuthController {
  /**
   * 用户注册
   */
  async register(req: Request, res: Response): Promise<void> {
    try {
      const { email, username, password } = req.body;

      // 调用认证服务进行注册
      const result = await authService.register({
        email,
        username,
        password,
      });

      ResponseUtil.success(res, {
        user: result.user,
        tokens: result.tokens,
      }, '注册成功', 201);

      logger.info(`用户注册成功: ${email}`);
    } catch (error: any) {
      logger.error('注册失败:', error);
      ResponseUtil.badRequest(res, error.message || '注册失败');
    }
  }

  /**
   * 用户登录
   */
  async login(req: Request, res: Response): Promise<void> {
    try {
      const { email, password } = req.body;

      // 调用认证服务进行登录
      const result = await authService.login({ email, password });

      ResponseUtil.success(res, {
        user: result.user,
        tokens: result.tokens,
      }, '登录成功');

      logger.info(`用户登录成功: ${email}`);
    } catch (error: any) {
      logger.error('登录失败:', error);
      ResponseUtil.unauthorized(res, error.message || '登录失败');
    }
  }

  /**
   * 刷新令牌
   */
  async refreshToken(req: Request, res: Response): Promise<void> {
    try {
      const { refreshToken } = req.body;

      // 调用认证服务刷新令牌
      const tokens = await authService.refreshToken(refreshToken);

      ResponseUtil.success(res, { tokens }, '令牌刷新成功');
    } catch (error: any) {
      logger.error('刷新令牌失败:', error);
      ResponseUtil.unauthorized(res, error.message || '刷新令牌失败');
    }
  }

  /**
   * 用户登出
   */
  async logout(req: Request, res: Response): Promise<void> {
    try {
      const user = req.user;
      const authHeader = req.headers.authorization;

      if (!user || !authHeader) {
        ResponseUtil.unauthorized(res, '未认证');
        return;
      }

      const accessToken = authHeader.substring(7); // 移除 "Bearer " 前缀

      // 调用认证服务进行登出
      await authService.logout(user.userId, accessToken);

      ResponseUtil.success(res, null, '登出成功');

      logger.info(`用户登出成功: ${user.userId}`);
    } catch (error: any) {
      logger.error('登出失败:', error);
      ResponseUtil.internalError(res, error.message || '登出失败');
    }
  }

  /**
   * 获取当前用户信息
   */
  async getCurrentUser(req: Request, res: Response): Promise<void> {
    try {
      const user = req.user;

      if (!user) {
        ResponseUtil.unauthorized(res, '未认证');
        return;
      }

      ResponseUtil.success(res, user, '获取用户信息成功');
    } catch (error: any) {
      logger.error('获取用户信息失败:', error);
      ResponseUtil.internalError(res, '获取用户信息失败');
    }
  }

  /**
   * 修改密码
   */
  async changePassword(req: Request, res: Response): Promise<void> {
    try {
      const user = req.user;
      const { oldPassword, newPassword } = req.body;

      if (!user) {
        ResponseUtil.unauthorized(res, '未认证');
        return;
      }

      // 调用认证服务修改密码
      await authService.changePassword(user.userId, oldPassword, newPassword);

      ResponseUtil.success(res, null, '密码修改成功');

      logger.info(`用户修改密码成功: ${user.userId}`);
    } catch (error: any) {
      logger.error('修改密码失败:', error);
      ResponseUtil.badRequest(res, error.message || '修改密码失败');
    }
  }

  /**
   * 发送密码重置邮件
   */
  async sendPasswordResetEmail(req: Request, res: Response): Promise<void> {
    try {
      const { email } = req.body;

      // 调用认证服务发送重置邮件
      await authService.sendPasswordResetEmail(email);

      ResponseUtil.success(res, null, '密码重置邮件已发送');

      logger.info(`密码重置邮件已发送: ${email}`);
    } catch (error: any) {
      logger.error('发送密码重置邮件失败:', error);
      ResponseUtil.badRequest(res, error.message || '发送密码重置邮件失败');
    }
  }

  /**
   * 重置密码
   */
  async resetPassword(req: Request, res: Response): Promise<void> {
    try {
      const { email, newPassword, resetCode } = req.body;

      // 调用认证服务重置密码
      await authService.resetPassword(email, newPassword, resetCode);

      ResponseUtil.success(res, null, '密码重置成功');

      logger.info(`密码重置成功: ${email}`);
    } catch (error: any) {
      logger.error('密码重置失败:', error);
      ResponseUtil.badRequest(res, error.message || '密码重置失败');
    }
  }
}

export default new AuthController();
